<template>
  <view class="container">
    <!-- 心理危机预警横幅 -->
    <view v-if="showWarning" class="warning-banner">
      <view class="warning-content">
        <text class="warning-icon">⚠️</text>
        <text class="warning-text">检测到可能需要紧急关注的内容！请务必联系专业心理援助！</text>
        <button class="warning-close" @click="showWarning = false">×</button>
      </view>
    </view>

    <!-- 顶部标题栏 -->
    <view class="header" :style="headerStyle">
      <text class="header-title">心灵助手小晴</text>
      <text class="header-subtitle">在线陪伴中</text>
    </view>

    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-container"
      scroll-y
      :scroll-top="scrollTop"
      scroll-with-animation
    >
      <block v-for="(item, index) in dialogs" :key="index">
        <!-- 在AI消息上方添加警示标记 -->
        <view v-if="item.showAlert" class="alert-marker">
          <text class="alert-text">⚠️ 已触发心理关注机制 ⚠️</text>
        </view>
        
        <!-- AI消息 -->
        <view v-if="item.role === 'ai'" class="ai-message">
          <view class="message-avatar">🤖</view>
          <view class="message-bubble">
            <text class="message-content">{{ item.content }}</text>
            <text class="message-time">{{ formatTime(item.created_at) }}</text>
          </view>
        </view>

        <!-- 用户消息 -->
        <view v-else class="user-message">
          <view class="message-bubble user">
            <text class="message-content">{{ item.content }}</text>
            <view class="message-status">
              <text class="message-time">{{ formatTime(item.created_at) }}</text>
              <view v-if="item.triggerWords.length > 0" class="trigger-words">
                触发关键词：{{ item.triggerWords.join('、') }}
              </view>
            </view>
          </view>
          <view class="message-avatar">👤</view>
        </view>
      </block>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-container">
      <textarea
        class="input-box"
        placeholder="和小晴聊聊你的心情..."
        v-model="inputContent"
        @confirm="sendMessage"
        cursor-spacing="20"
        auto-height
        :style="{ height: inputHeight + 'px' }"
        @input="updateInputHeight"
      />
      <button class="send-button" @click="sendMessage" :disabled="isLoading">
        {{ isLoading ? '回复中...' : '发送' }}
      </button>
    </view>
  </view>
</template>

<script>
import baseUrl from '../../static/path.js'
export default {
  data() {
    return {
      dialogs: [
        {
          role: 'ai',
          content: '你好呀！我是你的心灵助手小晴，有什么想和我聊聊的吗？',
          created_at: new Date(),
          showAlert: false
        }
      ],
      inputContent: '',
      scrollTop: 0,
      inputHeight: 80,
      isLoading: false,
      showWarning: false,
      // 心理危机关键词库
      warningKeywords: [
        '自杀', '自残', '不想活了', '跳楼', '安眠药',
        '抑郁症', '焦虑症', '崩溃', '绝望', '自杀倾向',
        '心理医生', '心理咨询', '活着没意思', '结束一切'
      ],
      // 标题栏预警样式
      headerStyle: ''
    }
  },
  created() {
    const token = uni.getStorageSync('access_token');
    if (!token) {
      uni.reLaunch({
        url: '/pages/login/login'
      });
    }
  },
  methods: {
    formatTime(date) {
      const d = new Date(date)
      return `${d.getHours()}:${d.getMinutes().toString().padStart(2, '0')}`
    },
    checkForWarning(content) {
      // 匹配精确的关键词（包括中英文符号）
      const regex = new RegExp(
        `(${this.warningKeywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`,
        'gi'
      )
      const matches = [...new Set(content.match(regex) || [])]
      return {
        trigger: matches.length > 0,
        words: matches
      }
    },
    async sendMessage() {
      if (!this.inputContent.trim()) return;

      // 执行心理预警检测
      const warningCheck = this.checkForWarning(this.inputContent)
      
      // 构建用户消息
      const userMessage = {
        role: 'user',
        content: this.inputContent,
        created_at: new Date(),
        triggerWords: warningCheck.words
      };

      this.dialogs.push(userMessage);
      
      // 如果触发关键词
      if (warningCheck.trigger) {
        this.showWarning = true
        this.startHeaderAlert()
        
        // 添加系统警示消息
        this.dialogs.push({
          role: 'ai',
          content: '检测到您可能需要紧急帮助，已为您启动心理关注机制。建议立即联系专业心理咨询：400-161-9995',
          created_at: new Date(),
          showAlert: true
        })
      }

      this.scrollToBottom();
      const token = uni.getStorageSync('access_token');
      
      // 发送请求...
      this.isLoading = true;
      try {
        const res = await uni.request({
          url: baseUrl + '/user/message',
          method: 'POST',
          header: {'Content-Type': 'application/json'},
          data: { token, message: this.inputContent }
        })
        
        if (res.statusCode === 200) {
          this.dialogs.push({
            role: 'ai',
            content: res.data.response.replace(/<think>[\s\S]*?<\/think>/g, '').trim(),
            created_at: new Date()
          })
        }
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
      
      this.inputContent = '';
    },
    startHeaderAlert() {
      let counter = 0
      const animate = () => {
        if (counter < 10) {
          this.headerStyle = `background-color: ${counter % 2 ? '#ff6666' : '#ff9999'};`
          counter++
          setTimeout(animate, 500)
        } else {
          this.headerStyle = ''
        }
      }
      animate()
    },
    scrollToBottom() {
      this.scrollTop = Date.now()
    },
    updateInputHeight(event) {
      const lines = event.detail.value.split('\n').length;
      this.inputHeight = 80 + (lines - 1) * 30;
    }
  }
}
</script>

<style>
	.warning-banner {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: #ff4444;
  color: white;
  padding: 20rpx;
  animation: alertFlash 1s infinite;
}

@keyframes alertFlash {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.warning-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.warning-icon {
  font-size: 40rpx;
  margin-right: 15rpx;
}

.warning-text {
  font-size: 30rpx;
  font-weight: bold;
}

.warning-close {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  color: white;
  font-size: 40rpx;
  background: transparent;
  padding: 0 20rpx;
}

.alert-marker {
  background: #fff3f3;
  border: 2rpx solid #ff4444;
  border-radius: 10rpx;
  padding: 15rpx;
  margin: 20rpx 0;
  text-align: center;
}

.alert-text {
  color: #ff4444;
  font-size: 28rpx;
  font-weight: bold;
}

.trigger-words {
  background: #ffe6e6;
  color: #cc0000;
  font-size: 24rpx;
  padding: 5rpx 10rpx;
  border-radius: 6rpx;
  margin-top: 10rpx;
}

/* 调整原有样式 */
.header {
  transition: background-color 0.5s;
}

.chat-container {
  margin-top: 80rpx; /* 给预警横幅留出空间 */
}

.user-message .message-status {
  flex-direction: column;
  align-items: flex-end;
}
.container {
  height: 800px;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #b3d9ff; /* 头部背景色 */
  padding: 30rpx; /* 头部内边距 */
  border-bottom: 2rpx solid #99ccff; /* 头部底边框 */
}

.header-title {
  font-size: 38rpx; /* 头部标题字体大小 */
  color: #2c3e50; /* 头部标题字体颜色 */
  font-weight: bold; /* 头部标题字体加粗 */
  display: block; /* 块级显示 */
}

.header-subtitle {
  font-size: 24rpx; /* 头部副标题字体大小 */
  color: #666; /* 头部副标题字体颜色 */
  display: block; /* 块级显示 */
}

.chat-container {
  flex: 1; /* 填充剩余空间 */
  padding: 20rpx; /* 聊天区域内边距 */
  overflow-y: auto; /* 允许垂直滚动 */
}

/* 消息通用样式 */
.message-bubble {
  max-width: 500rpx; /* 消息气泡最大宽度 */
  padding: 20rpx; /* 消息气泡内边距 */
  border-radius: 12rpx; /* 消息气泡圆角 */
  position: relative; /* 相对定位 */
  margin: 20rpx 0; /* 消息气泡外边距 */
}

/* AI消息样式 */
.ai-message {
  display: flex; /* 灵活布局 */
  justify-content: flex-start; /* 左对齐 */
  align-items: flex-start; /* 顶部对齐 */
}

.ai-message .message-bubble {
  background: #fff; /* AI消息背景 */
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08); /* AI消息阴影 */
  margin-left: 20rpx; /* AI消息左边距 */
}

/* 用户消息样式 */
.user-message {
  display: flex; /* 灵活布局 */
  justify-content: flex-end; /* 右对齐 */
  align-items: flex-start; /* 顶部对齐 */
}

.user-message .message-bubble {
  background: linear-gradient(135deg, #99ccff, #6699ff); /* 用户消息渐变背景 */
  color: white; /* 用户消息字体颜色 */
  margin-right: 20rpx; /* 用户消息右边距 */
}

.message-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%; 
  background: #e6f2ff; 
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 50rpx;
}

.message-content {
  font-size: 32rpx;
  line-height: 1.5;
}

.message-time {
  font-size: 24rpx;
  color: #ffffff;
  margin-left: 20rpx;
}

.message-status {
  display: flex;
  align-items: center; 
  justify-content: flex-end; 
  margin-top: 10rpx;
}

.emotion-indicator {
  font-size: 40rpx;
  margin-left: 10rpx;
}

.input-container {
  border-top: 2rpx solid #e0e0e0;
  padding: 20rpx;
  background: white;
  display: flex; 
  align-items: center; 
}

.input-box {
  flex: 1;
  background: #f0f7ff; 
  border-radius: 40rpx;
  padding: 20rpx 30rpx;
  min-height: 80rpx;
  max-height: 200rpx;
  margin-right: 20rpx;
  resize: none;
}

.send-button {
  background: #6699ff;
  color: white;
  border-radius: 40rpx;
  padding: 0 40rpx;
  height: 80rpx;
  line-height: 80rpx; 
  font-size: 32rpx; 
}
.warning-banner {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: #ff4444;
  color: white;
  padding: 20rpx;
  animation: alertFlash 1s infinite;
}

@keyframes alertFlash {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.warning-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.warning-icon {
  font-size: 40rpx;
  margin-right: 15rpx;
}

.warning-text {
  font-size: 30rpx;
  font-weight: bold;
}

.warning-close {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  color: white;
  font-size: 40rpx;
  background: transparent;
  padding: 0 20rpx;
}

.alert-marker {
  background: #fff3f3;
  border: 2rpx solid #ff4444;
  border-radius: 10rpx;
  padding: 15rpx;
  margin: 20rpx 0;
  text-align: center;
}

.alert-text {
  color: #ff4444;
  font-size: 28rpx;
  font-weight: bold;
}

.trigger-words {
  background: #ffe6e6;
  color: #cc0000;
  font-size: 24rpx;
  padding: 5rpx 10rpx;
  border-radius: 6rpx;
  margin-top: 10rpx;
}
</style>
